"""
系统配置相关路由
"""
from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from models import PortConfigRequest, PortConfigResponse, APIResponse
from config import settings
import os
import signal

router = APIRouter(prefix="/api/system", tags=["System"])

@router.get("/config/port", response_model=PortConfigResponse)
async def get_port_config():
    """获取当前端口配置"""
    return PortConfigResponse(
        current_port=settings.PORT,
        host=settings.HOST
    )

@router.post("/config/port")
async def update_port_config(request: PortConfigRequest):
    """更新端口配置"""
    if not (1 <= request.port <= 65535):
        raise HTTPException(
            status_code=400, 
            detail="端口号必须在1-65535范围内"
        )
    
    # 检查端口是否被占用
    import socket
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((settings.HOST, request.port))
        sock.close()
        
        if result == 0 and request.port != settings.PORT:
            raise HTTPException(
                status_code=400,
                detail=f"端口 {request.port} 已被占用"
            )
    except Exception:
        pass
    
    # 更新配置
    if settings.update_port(request.port):
        return APIResponse(
            success=True,
            message=f"端口配置已更新为 {request.port}，需要重启服务生效",
            data={
                "old_port": settings.PORT,
                "new_port": request.port,
                "restart_required": True
            }
        )
    else:
        raise HTTPException(
            status_code=500,
            detail="保存配置失败"
        )

@router.post("/restart")
async def restart_service():
    """重启服务（仅在systemd管理下有效）"""
    try:
        # 发送重启信号
        os.kill(os.getpid(), signal.SIGUSR1)
        return APIResponse(
            success=True,
            message="正在重启服务..."
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"重启失败: {str(e)}"
        )

@router.get("/info")
async def get_system_info():
    """获取系统信息"""
    import platform
    import psutil
    
    return {
        "system": {
            "platform": platform.platform(),
            "python_version": platform.python_version(),
            "architecture": platform.architecture()[0]
        },
        "service": {
            "name": settings.APP_NAME,
            "version": settings.VERSION,
            "host": settings.HOST,
            "port": settings.PORT
        },
        "resources": {
            "cpu_percent": psutil.cpu_percent(),
            "memory_percent": psutil.virtual_memory().percent,
            "disk_percent": psutil.disk_usage('/').percent
        }
    }